/**
 * Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
 * <p>
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE 3.0;
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springblade.modules.bank.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.NumberUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.FileUtils;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import lombok.AllArgsConstructor;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.Charsets;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.BladeUser;
import org.springblade.core.secure.utils.SecureUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.bank.entity.*;
import org.springblade.modules.bank.excel.TmVisitTaskExcel;
import org.springblade.modules.bank.service.*;
import org.springblade.modules.bank.util.AESUtil;
import org.springblade.modules.bank.util.BusFileUtil;
import org.springblade.modules.bank.vo.*;
import org.springblade.modules.system.entity.Dept;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.modules.system.service.IUserService;
import org.springblade.modules.system.vo.UserVO;
import org.springblade.modules.system.wrapper.UserWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestParam;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springblade.core.boot.ctrl.BladeController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;

import static org.springblade.modules.bank.constant.BankConstant.EX1_TYPE_BUSINESS;
import static org.springblade.modules.bank.constant.BankConstant.EX1_TYPE_DAILY;

/**
 * 拜访任务 控制器
 *
 * @author Blade
 * @since 2022-07-08
 */
@RestController
@AllArgsConstructor
@RequestMapping("/tmvisittask")
@Api(value = "拜访任务", tags = "拜访任务接口")
@Slf4j
public class TmVisitTaskController extends BladeController {

    private ITmVisitTaskService tmVisitTaskService;
    private ITmVisitTaskCustomerService tmVisitTaskCustomerService;
    private ITmVisitTaskCustMgrService tmVisitTaskCustMgrService;
    private IUserService userService;
    private ITmCustomerService customerService;
    private IDeptService deptService;
    private ITmCustomerCallRecordService tmCustomerCallRecordService;
    private ITmDailyTaskLogService tmDailyTaskLogService;

    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

    private ITmExcelImportLogService tmExcelImportLogService;

    private Environment environment;
    /**
     * 详情
     */
    @GetMapping("/detail")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "详情", notes = "传入tmVisitTask")
    public R<TmVisitTask> detail(TmVisitTask tmVisitTask) {
        TmVisitTask detail = tmVisitTaskService.getOne(Condition.getQueryWrapper(tmVisitTask));
        return R.data(detail);
    }

    /**
     * 分页 拜访任务
     */
    @GetMapping("/list")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "分页", notes = "传入tmVisitTask")
    public R<IPage<TmVisitTask>> list(TmVisitTask tmVisitTask, Query query) {
        QueryWrapper queryWrapper;
        if ("apply".equals(tmVisitTask.getPageName())) {
            queryWrapper = Condition.getQueryWrapper(tmVisitTask);
            if (null != tmVisitTask.getChargeDateBegin() && null != tmVisitTask.getChargeDateEnd()) {
                queryWrapper.between("charge_date", tmVisitTask.getChargeDateBegin(), tmVisitTask.getChargeDateEnd());
            }
            if (null != tmVisitTask.getTaskStatus() && !"".equals(tmVisitTask.getTaskStatus())) {
                queryWrapper.eq("task_status", tmVisitTask.getTaskStatus());
            } else {
                queryWrapper.in("task_status", "1", "2", "3", "4");
            }
            if (null != tmVisitTask.getScriptStatus() && !"".equals(tmVisitTask.getScriptStatus())) {
                queryWrapper.eq("script_status", tmVisitTask.getScriptStatus());
            }
        } else if ("approve".equals(tmVisitTask.getPageName())) {
            queryWrapper = Condition.getQueryWrapper(tmVisitTask);
            if (null != tmVisitTask.getChargeDateBegin() && null != tmVisitTask.getChargeDateEnd()) {
                queryWrapper.between("charge_date", tmVisitTask.getChargeDateBegin(), tmVisitTask.getChargeDateEnd());
            }
            if (null != tmVisitTask.getTaskStatus() && !"".equals(tmVisitTask.getTaskStatus())) {
                queryWrapper.eq("task_status", tmVisitTask.getTaskStatus());
            } else {
                queryWrapper.in("task_status", "2", "4");
            }
            if (null != tmVisitTask.getScriptStatus() && !"".equals(tmVisitTask.getScriptStatus())) {
                queryWrapper.eq("script_status", tmVisitTask.getScriptStatus());
            }
            if (tmVisitTask.getDataPermission()!=null){
                if (tmVisitTask.getDataPermission()==1){}
                else if(tmVisitTask.getDataPermission()==2){
                    List<Dept> deptList = deptService.list(new LambdaQueryWrapper<Dept>().eq(Dept::getParentId,tmVisitTask.getQueryParentDeptId()));
                    List<Long> deptIdList = deptList.stream().map(item->item.getId()).collect(Collectors.toList());
                    if (deptIdList.size()==0){
                        return R.data(null);
                    }
                    queryWrapper.in("dept_id",deptIdList);
                }else if(tmVisitTask.getDataPermission()==3){
                    queryWrapper.eq("dept_id",tmVisitTask.getQueryDeptId());
                }
            }
        } else if ("query".equals(tmVisitTask.getPageName())) {
            queryWrapper = Condition.getQueryWrapper(tmVisitTask);
            if (null != tmVisitTask.getChargeDateBegin() && null != tmVisitTask.getChargeDateEnd()) {
                queryWrapper.between("charge_date", tmVisitTask.getChargeDateBegin(), tmVisitTask.getChargeDateEnd());
            }
            if (null != tmVisitTask.getTaskStatus() && !"".equals(tmVisitTask.getTaskStatus())) {
                queryWrapper.eq("task_status", tmVisitTask.getTaskStatus());
            }
            if (null != tmVisitTask.getScriptStatus() && !"".equals(tmVisitTask.getScriptStatus())) {
                queryWrapper.eq("script_status", tmVisitTask.getScriptStatus());
            }
        } else {
            queryWrapper = Condition.getQueryWrapper(tmVisitTask);
        }
        queryWrapper.orderByDesc("charge_date");
        queryWrapper.orderByAsc("seq");
        IPage<TmVisitTask> pages = tmVisitTaskService.page(Condition.getPage(query), queryWrapper);
        return R.data(pages);
    }

    /**
     * 自定义分页 拜访任务
     */
    @GetMapping("/page")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "分页", notes = "传入tmVisitTask")
    public R<IPage<TmVisitTaskVO>> page(TmVisitTaskVO tmVisitTask, Query query) {
        IPage<TmVisitTaskVO> pages = tmVisitTaskService.selectTmVisitTaskPage(Condition.getPage(query), tmVisitTask);
        return R.data(pages);
    }

	/**
	 * 自定义分页 拜访任务
	 */
	@GetMapping("/getVistList")
	@ApiOperationSupport(order = 3)
	@ApiOperation(value = "分页", notes = "传入tmVisitTask")
	public R<IPage<VisitTaskVO>> getVistList(TmVisitTaskVO tmVisitTask, Query query) {
		IPage<VisitTaskVO> pages = tmVisitTaskService.getVistList(Condition.getPage(query), tmVisitTask);
		return R.data(pages);
	}

    /**
     * 新增 拜访任务
     */
    @PostMapping("/save")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "新增", notes = "传入tmVisitTask")
    public R save(@Valid @RequestBody TmVisitTask tmVisitTask) {
        if ("".equals(tmVisitTask.getScriptDesc()) || null == tmVisitTask.getScriptDesc()) {
            tmVisitTask.setScriptStatus("0");
        } else {
            tmVisitTask.setScriptStatus("1");
        }
        return R.status(tmVisitTaskService.save(tmVisitTask));
    }

    /**
     * 修改 拜访任务
     */
    @PostMapping("/update")
    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "修改", notes = "传入tmVisitTask")
    public R update(@Valid @RequestBody TmVisitTask tmVisitTask) {
        if ("".equals(tmVisitTask.getScriptDesc()) || null == tmVisitTask.getScriptDesc()) {
            tmVisitTask.setScriptStatus("0");
        } else {
            tmVisitTask.setScriptStatus("1");
        }
        return R.status(tmVisitTaskService.updateById(tmVisitTask));
    }

    /**
     * 新增或修改 拜访任务
     */
    @PostMapping("/submit")
    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "新增或修改", notes = "传入tmVisitTask")
    public R submit(@Valid @RequestBody TmVisitTask tmVisitTask) {
        tmVisitTask.setCustNumber(null);
        String option = "add";
        if ("".equals(tmVisitTask.getScriptDesc()) || null == tmVisitTask.getScriptDesc()) {
            tmVisitTask.setScriptStatus("0");
        } else {
            tmVisitTask.setScriptStatus("1");
        }
        BladeUser bladeUser = SecureUtil.getUser();
        if (null == tmVisitTask.getId()) {
            tmVisitTask.setCreateBy(bladeUser.getUserId());
            tmVisitTask.setChargeDate(LocalDate.now());
            tmVisitTask.setChargeUserId(bladeUser.getUserId());
            tmVisitTask.setChargeUserName(bladeUser.getUserName());
            tmVisitTask.setTaskType("1");
            tmVisitTask.setEx1(EX1_TYPE_BUSINESS);
        } else {
            tmVisitTask.setUpdateBy(bladeUser.getUserId());
//            QueryWrapper<TmVisitTaskCustomer> queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("task_id", tmVisitTask.getId());
//            long count = tmVisitTaskCustomerService.count(queryWrapper);
//            tmVisitTask.setCustNumber((int) count);
            //审批记录
            if ("4".equals(tmVisitTask.getTaskStatus())) {
                option = "audit";
                tmVisitTask.setAuditUserId(bladeUser.getUserId());
                tmVisitTask.setAuditUserName(bladeUser.getUserName());
                tmVisitTask.setAuditTime(LocalDateTime.now());
            }
        }
        AtomicReference<String> meg = new AtomicReference<>("");
        if ("audit".equals(option)) {
            List<TmVisitTaskCustomer> tmVisitTaskCustomers = tmVisitTaskCustomerService.list(new QueryWrapper<TmVisitTaskCustomer>().lambda()
                    .eq(TmVisitTaskCustomer::getTaskId, tmVisitTask.getId()));
            List<TmCustomer> addCustomer = new ArrayList<>();
            tmVisitTaskCustomers.forEach(customer -> {
                String aesCustomerName = "";
                String aesCustomerPhone = "";
                if("2".equals(tmVisitTask.getTaskType())){
                    try {
                        if(null != customer.getCustomerPhone() && !"".equals(customer.getCustomerPhone())){
                            aesCustomerPhone = AESUtil.encrypt(customer.getCustomerPhone(),BankConstants.KEY);
                        }
                        if(null != customer.getEx1() && !"".equals(customer.getEx1())){
                            aesCustomerName = AESUtil.encrypt(customer.getEx1(),BankConstants.KEY);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                long count = customerService.count(new QueryWrapper<TmCustomer>().lambda()
                        .eq(TmCustomer::getCustomerCode, customer.getCustomerCode()));
                if (0 == count) {
                    TmCustomer tmCustomer = new TmCustomer();
                    tmCustomer.setCustomerCode(customer.getCustomerCode());
                    tmCustomer.setCustMgr(customer.getCustMgr());
                    User user = userService.getOne(new QueryWrapper<User>().lambda().eq(User::getCode, customer.getCustMgr()));
                    tmCustomer.setCustMgrName(user.getRealName());
                    tmCustomer.setDeptId(tmVisitTask.getDeptId());
                    tmCustomer.setDeptName(tmVisitTask.getDeptName());
                    tmCustomer.setSex(customer.getSex());
                    if("2".equals(tmVisitTask.getTaskType())){ //导入数据含有电话号码加密
                        tmCustomer.setCustomerTel(aesCustomerPhone);
                        tmCustomer.setCustomerName(aesCustomerName);
                    }
                    tmCustomer.setCustOrigin(tmVisitTask.getTaskType());
                    addCustomer.add(tmCustomer);
                }else {
                    //有更新部门、性别
                    customerService.update(new UpdateWrapper<TmCustomer>().lambda()
                            .eq(TmCustomer::getCustomerCode,customer.getCustomerCode())
                            .set(TmCustomer::getDeptId,tmVisitTask.getDeptId())
                            .set(TmCustomer::getDeptName,tmVisitTask.getDeptName())
                            .set(TmCustomer::getSex,customer.getSex()));
                }
                if("2".equals(tmVisitTask.getTaskType())) {
                    //更新完成删除任务客户电话号码
                    tmVisitTaskCustomerService.update(new UpdateWrapper<TmVisitTaskCustomer>().lambda()
                            .eq(TmVisitTaskCustomer::getId, customer.getId())
                            .set(TmVisitTaskCustomer::getCustomerPhone, null)
                            .set(TmVisitTaskCustomer::getEx1,null));
                }
            });
            customerService.saveBatch(addCustomer);
        }
        boolean b = tmVisitTaskService.saveOrUpdate(tmVisitTask);
        return R.data(tmVisitTask);

    }


    /**
     * 批量提交、审核方法
     */
    @PostMapping("/batchSubmits")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "批量提交、审核方法", notes = "传入ids")
    public R batchSubmits(@ApiParam(value = "批量提交、审核方法", required = true) @RequestParam String ids, String option) {
        BladeUser bladeUser = SecureUtil.getUser();
        List<Long> longs = Func.toLongList(ids);
        longs.forEach(item -> {
            UpdateWrapper<TmVisitTask> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("task_status", option);
            if ("4".equals(option)) {
                updateWrapper.set("audit_user_id", bladeUser.getUserId());
                updateWrapper.set("audit_user_name", bladeUser.getUserName());
                updateWrapper.set("audit_time", LocalDateTime.now());
            }
            updateWrapper.eq("id", item);
            //查询部门信息
            if ("4".equals(option)) {
                TmVisitTask tmVisitTask = tmVisitTaskService.getById(item);
                List<TmVisitTaskCustomer> tmVisitTaskCustomers = tmVisitTaskCustomerService.list(new QueryWrapper<TmVisitTaskCustomer>().lambda()
                        .eq(TmVisitTaskCustomer::getTaskId, item));
                TmVisitTask byId = tmVisitTaskService.getById(item);
                List<TmCustomer> addCustomer = new ArrayList<>();
                tmVisitTaskCustomers.forEach(customer -> {
                    long count = customerService.count(new QueryWrapper<TmCustomer>().lambda()
                            .eq(TmCustomer::getCustomerCode, customer.getCustomerCode()));
                    TmCustomer tmCustomer = new TmCustomer();
                    String aesCustomerName = "";
                    String aesCustomerPhone = "";
                    if("2".equals(tmVisitTask.getTaskType())){
                        try {
                            if(null != customer.getCustomerPhone() && !"".equals(customer.getCustomerPhone())){
                                aesCustomerPhone = AESUtil.encrypt(customer.getCustomerPhone(),BankConstants.KEY);
                            }
                            if(null != customer.getEx1() && !"".equals(customer.getEx1())){
                                aesCustomerName = AESUtil.encrypt(customer.getEx1(),BankConstants.KEY);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                    if (count == 0) { //没有插入
                        tmCustomer.setCustomerCode(customer.getCustomerCode());
                        tmCustomer.setCustMgr(customer.getCustMgr());
                        User user = userService.getOne(new QueryWrapper<User>().lambda().eq(User::getCode, customer.getCustMgr()));
                        tmCustomer.setCustMgrName(user.getRealName());
                        tmCustomer.setDeptId(byId.getDeptId());
                        tmCustomer.setDeptName(byId.getDeptName());
                        tmCustomer.setSex(customer.getSex());
                        tmCustomer.setCustOrigin(byId.getTaskType());
                        if("2".equals(tmVisitTask.getTaskType())){ //导入数据含有电话号码加密
                            tmCustomer.setCustomerTel(aesCustomerPhone);
                            tmCustomer.setCustomerName(aesCustomerName);
                        }
                        addCustomer.add(tmCustomer);
                    }else { //有更新部门、性别
                        customerService.update(new UpdateWrapper<TmCustomer>().lambda()
                                .eq(TmCustomer::getCustomerCode,customer.getCustomerCode())
                                .set(TmCustomer::getDeptId,byId.getDeptId())
                                .set(TmCustomer::getDeptName,byId.getDeptName())
                                .set(TmCustomer::getSex,customer.getSex()));
                    }
                    if("2".equals(tmVisitTask.getTaskType())) {
                        //更新完成删除任务客户电话号码
                        tmVisitTaskCustomerService.update(new UpdateWrapper<TmVisitTaskCustomer>().lambda()
                                .eq(TmVisitTaskCustomer::getId, customer.getId())
                                .set(TmVisitTaskCustomer::getCustomerPhone, null)
                                .set(TmVisitTaskCustomer::getEx1,null));
                    }
                });
                customerService.saveBatch(addCustomer);
            }
            boolean update = tmVisitTaskService.update(updateWrapper);
        });
        return R.success("执行成功");
    }

    /**
     * 批量维护营销话术
     */
    @PostMapping("/batchEditScriptDesc")
    @ApiOperationSupport(order = 10)
    @ApiOperation(value = "批量维护营销话术", notes = "传入ids")
    public R batchEditScriptDesc(@ApiParam(value = "批量维护营销话术", required = true) @RequestParam String ids, String scriptDesc) {
        List<Long> longs = Func.toLongList(ids);
        longs.forEach(item -> {
            LambdaUpdateWrapper<TmVisitTask> updateWrapper = new UpdateWrapper<TmVisitTask>().lambda()
                    .set(TmVisitTask::getScriptDesc, scriptDesc)
                    .set(TmVisitTask::getScriptStatus, "1")
                    .eq(TmVisitTask::getId, item);
            tmVisitTaskService.update(updateWrapper);
        });
        return R.success("执行成功");
    }

    /**
     * 批量驳回
     */
    @PostMapping("/batchRejected")
    @ApiOperationSupport(order = 11)
    @ApiOperation(value = "批量驳回", notes = "传入ids")
    public R batchRejected(@ApiParam(value = "主键集合", required = true) @RequestParam String ids, String reason) {
        List<Long> longs = Func.toLongList(ids);
        longs.forEach(item -> {
            LambdaUpdateWrapper<TmVisitTask> updateWrapper = new UpdateWrapper<TmVisitTask>().lambda();
            updateWrapper.set(TmVisitTask::getReason, reason);
            updateWrapper.set(TmVisitTask::getTaskStatus, "3");
            updateWrapper.eq(TmVisitTask::getId, item);
            tmVisitTaskService.update(updateWrapper);
        });
        return R.success("执行成功");
    }

    /**
     * 删除 拜访任务
     */
    @PostMapping("/remove")
    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "逻辑删除", notes = "传入ids")
    public R remove(@ApiParam(value = "主键集合", required = true) @RequestParam String ids) {
//		先删除子表数据，再删除主表数据；
        List<Long> longs = Func.toLongList(ids);
        LambdaQueryWrapper<TmVisitTaskCustomer> queryWrapper = new QueryWrapper<TmVisitTaskCustomer>().lambda();
        queryWrapper.in(TmVisitTaskCustomer::getTaskId, longs);
        tmVisitTaskCustomerService.remove(queryWrapper);
        return R.status(tmVisitTaskService.removeByIds(Func.toLongList(ids)));
    }

    /**
     * 查询今天已有的任务数
     *
     * @return
     */
    @GetMapping("/getNewTaskNum")
    @ApiOperationSupport(order = 8)
    @ApiOperation(value = "查询今天已有的任务数", notes = "无需传参")
    public long getNewTaskNum() {
        LambdaQueryWrapper<TmVisitTask> queryWrapper = new QueryWrapper<TmVisitTask>().lambda().eq(TmVisitTask::getChargeDate, LocalDate.now());
        long count = tmVisitTaskService.count(queryWrapper);
        return count;
    }

    /**
     * 任务导入
     */
    @PostMapping("/visitTaskimport")
    @ApiOperationSupport(order = 12)
    @ApiOperation(value = "任务导入", notes = "传入excel")
    public R importUser(MultipartFile file, Integer isCovered) {
        String filename = file.getOriginalFilename();
        if (StringUtils.isEmpty(filename)) {
            throw new RuntimeException("请上传文件!");
        }
        if ((!StringUtils.endsWithIgnoreCase(filename, ".xls") && !StringUtils.endsWithIgnoreCase(filename, ".xlsx"))) {
            throw new RuntimeException("请上传正确的excel文件!");
        }

        TmExcelImportLog tmExcelImportLog = new TmExcelImportLog();
        tmExcelImportLog.setImportType("商机任务导入");
        tmExcelImportLog.setFlag("导入失败");
        BusFileUtil.uploadFile(tmExcelImportLog,file,environment.getProperty("recordFilePath"));
//        tmExcelImportLogService.save(tmExcelImportLog);

        List<TmVisitTaskExcel> list = new ArrayList<>(); //定义excel表格数据
        AnalysisEventListener<TmVisitTaskExcel> analysisEventListener = new AnalysisEventListener<TmVisitTaskExcel>() {
            // 这个每一条数据解析都会来调用
            @Override
            public void invoke(TmVisitTaskExcel data, AnalysisContext context) {
                list.add(data);
                // TODO 这里也可以对数据进行操作
            }

            // 所有数据解析完成了都会来调用
            @Override
            public void doAfterAllAnalysed(AnalysisContext context) {
                // TODO 这里也可以对数据进行操作
            }
        };
        InputStream inputStream;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            return null;
        }
        EasyExcel.read(inputStream, TmVisitTaskExcel.class, analysisEventListener).sheet().doRead();
        BladeUser bladeUser = SecureUtil.getUser();
        Map<String, User> custMgrMap = new HashMap<>();
        Map<String, Dept> deptMap = new HashMap<>();
        Map<String, String> dept_taskMap = new HashMap<>();
        Map<String, String> customerMap = new HashMap<>();
        Map<String, String> customerPhoneMap = new HashMap<>();
        Map<String, TmVisitTaskExcel> mainMap = new HashMap<>();
        List<TmVisitTask> addTask = new ArrayList<>();
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");

        for (TmVisitTaskExcel tmVisitTaskExcel : list) {
            if(null == tmVisitTaskExcel.getTaskName() || "".equals(tmVisitTaskExcel.getTaskName()) )
                return R.fail("任务名称不能为空！请检查");
            if(null == tmVisitTaskExcel.getTaskLevel() || "".equals(tmVisitTaskExcel.getTaskLevel()) )
                return R.fail("任务级别不能为空！请检查");
            if(null == tmVisitTaskExcel.getDeptName() || "".equals(tmVisitTaskExcel.getDeptName()) )
                return R.fail("网点名称不能为空！请检查");
            if(null == tmVisitTaskExcel.getCustMgr() || "".equals(tmVisitTaskExcel.getCustMgr()) )
                return R.fail("员工编号不能为空！请检查");
            if(null == tmVisitTaskExcel.getTaskBeginDate() || "".equals(tmVisitTaskExcel.getTaskBeginDate()) )
                return R.fail("任务起始日期不能为空！请检查");
            if(null == tmVisitTaskExcel.getTaskEndDate() || "".equals(tmVisitTaskExcel.getTaskEndDate()) )
                return R.fail("任务截止日期不能为空！请检查");
            // 判断客户经理是否存在
            if (!custMgrMap.containsKey(tmVisitTaskExcel.getCustMgr())) {
                User user = userService.getOne(new QueryWrapper<User>().lambda().eq(User::getCode, tmVisitTaskExcel.getCustMgr()));
                if (null == user) {
                    return R.fail("员工编码" + tmVisitTaskExcel.getCustMgr() + "不存在！请检查");
                } else {
                    custMgrMap.put(tmVisitTaskExcel.getCustMgr(), user);
                }
            }
            // 判断部门是否存在
            if (!deptMap.containsKey(tmVisitTaskExcel.getDeptName())) {
                List<Dept> deptList = deptService.list(new QueryWrapper<Dept>().lambda().eq(Dept::getDeptName, tmVisitTaskExcel.getDeptName()));
                if (deptList.size() > 0) {
                    deptMap.put(deptList.get(0).getDeptName(), deptList.get(0));
                } else {
                    return R.fail("网点" + tmVisitTaskExcel.getDeptName() + "不存在！请检查");
                }
            }
            // 判断一个部门是否只有一个任务
            if (!dept_taskMap.containsKey(tmVisitTaskExcel.getDeptName())) {
                dept_taskMap.put(tmVisitTaskExcel.getDeptName(), tmVisitTaskExcel.getTaskName());
            } else {
                if (!dept_taskMap.get(tmVisitTaskExcel.getDeptName()).equals(tmVisitTaskExcel.getTaskName())) {
                    return R.fail(tmVisitTaskExcel.getDeptName() + "网点一次导入只能有一条任务！请检查");
                }
            }
            // 判断起始日期是否小于等于截至日期
            if (tmVisitTaskExcel.getTaskBeginDate().compareTo(tmVisitTaskExcel.getTaskEndDate()) == 1) {
                return R.fail("员工编码" + tmVisitTaskExcel.getCustomerCode() + "的起始日期大于截至日期！请检查");
            }

            //判断同一个任务起始日期和截至日期是否相同
            if (!mainMap.containsKey(tmVisitTaskExcel.getDeptName())) {
                mainMap.put(tmVisitTaskExcel.getDeptName(), tmVisitTaskExcel);
//                任务主表数据
                TmVisitTask tmVisitTask = new TmVisitTask();
                tmVisitTask.setTaskName(tmVisitTaskExcel.getTaskName());
                tmVisitTask.setDeptId(String.valueOf(deptMap.get(tmVisitTaskExcel.getDeptName()).getId()));
                tmVisitTask.setDeptName(tmVisitTaskExcel.getDeptName());
                tmVisitTask.setChargeUserId(bladeUser.getUserId());
                tmVisitTask.setTaskLevel(tmVisitTaskExcel.getTaskLevel());
                tmVisitTask.setChargeUserName(bladeUser.getUserName());
                tmVisitTask.setChargeDate(LocalDate.now());
//                tmVisitTask.setCustNumber(tmVisitTaskExcel.getCustNumber());
                ZoneId zoneId = ZoneId.systemDefault();
                Instant instant = tmVisitTaskExcel.getTaskBeginDate().toInstant();
                LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zoneId);
                tmVisitTask.setTaskBeginDate(localDateTime.toLocalDate());
                Instant endinstant = tmVisitTaskExcel.getTaskEndDate().toInstant();
                LocalDateTime endlocalDateTime = LocalDateTime.ofInstant(endinstant, zoneId);
                tmVisitTask.setTaskEndDate(endlocalDateTime.toLocalDate());
                tmVisitTask.setTaskType("2");
                tmVisitTask.setTaskStatus("1");
                tmVisitTask.setScriptDesc("0");
                tmVisitTask.setCreateBy(bladeUser.getUserId());
                tmVisitTask.setDelFlag(-1);
                //商机任务
                tmVisitTask.setEx1(EX1_TYPE_BUSINESS);
                addTask.add(tmVisitTask);
            } else {
                if (!tmVisitTaskExcel.getTaskBeginDate().equals(mainMap.get(tmVisitTaskExcel.getDeptName()).getTaskBeginDate())) {
                    return R.fail(tmVisitTaskExcel.getTaskName() + "任务起始日期" + sdf.format(mainMap.get(tmVisitTaskExcel.getDeptName()).getTaskBeginDate()) + "和起始日期" + sdf.format(tmVisitTaskExcel.getTaskBeginDate()) + "不相同！请检查");
                } else if (!tmVisitTaskExcel.getTaskEndDate().equals(mainMap.get(tmVisitTaskExcel.getDeptName()).getTaskEndDate())) {
                    return R.fail(tmVisitTaskExcel.getTaskName() + "任务截至日期" + sdf.format(mainMap.get(tmVisitTaskExcel.getDeptName()).getTaskEndDate()) + "和截至日期" + sdf.format(tmVisitTaskExcel.getTaskEndDate()) + "不相同！请检查");
                } else if (!tmVisitTaskExcel.getTaskBeginDate().equals(mainMap.get(tmVisitTaskExcel.getDeptName()).getTaskBeginDate())
                        && !tmVisitTaskExcel.getTaskEndDate().equals(mainMap.get(tmVisitTaskExcel.getDeptName()).getTaskEndDate())) {
                    return R.fail(tmVisitTaskExcel.getTaskName() + "任务存在起始日期和截日期不相同！请检查");
                }
            }

        };
        for (TmVisitTaskExcel excelRow : list) {
            // 判断客户经理是否存在对应部门
            User user = custMgrMap.get(excelRow.getCustMgr());
            Dept dept = deptMap.get(excelRow.getDeptName());
            if (!user.getDeptId().equals(dept.getId().toString())) {
                return R.fail(dept.getDeptName() + "不存在客户经理" + user.getCode() + "_" + user.getName() + "！请检查");
            }
        }
        addTask.forEach(item -> {
            LambdaQueryWrapper<TmVisitTask> queryWrapper = new QueryWrapper<TmVisitTask>().lambda().eq(TmVisitTask::getChargeDate, LocalDate.now());
            long count = tmVisitTaskService.count(queryWrapper);
            Integer num = Integer.valueOf((int) count) +1;
            if(num<10){
                item.setTaskCode(format.format(new Date())+"00".concat(String.valueOf(num)));
            }else {
                item.setTaskCode(format.format(new Date())+"0".concat(String.valueOf(num)));
            }
            boolean save = tmVisitTaskService.save(item);
            if(save){
//                组织子表数据
                List<TmVisitTaskCustMgr> addTmVisitTaskCustMgr = new ArrayList<>();
                int custNumberPlan = 0;
                for (TmVisitTaskExcel excelInfo : list) {
                    if(item.getTaskName().equals(excelInfo.getTaskName())
                            &&item.getDeptName().equals(excelInfo.getDeptName())){
                        TmVisitTaskCustMgr tmVisitTaskCustMgr = new TmVisitTaskCustMgr();
                        tmVisitTaskCustMgr.setDeptTaskId(item.getId());
                        tmVisitTaskCustMgr.setCustMgr(excelInfo.getCustMgr());
                        tmVisitTaskCustMgr.setCustMgrName(custMgrMap.get(excelInfo.getCustMgr()).getRealName());
                        tmVisitTaskCustMgr.setCustNumberPlan(excelInfo.getCustNumber());
                        tmVisitTaskCustMgr.setTaskType(EX1_TYPE_BUSINESS);
                        addTmVisitTaskCustMgr.add(tmVisitTaskCustMgr);

                        custNumberPlan += excelInfo.getCustNumber()==null?0:excelInfo.getCustNumber();
                    }
                };
                boolean b = tmVisitTaskCustMgrService.saveBatch(addTmVisitTaskCustMgr);
                if(b){
                    // 子表保存成功查询客户数，更新主表客户数
                    UpdateWrapper<TmVisitTask> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.set("cust_number",custNumberPlan);
                    updateWrapper.eq("id",item.getId());
                    tmVisitTaskService.update(updateWrapper);
                }
            }
        });

        tmExcelImportLog.setCompleteTime(LocalDateTime.now());
        tmExcelImportLog.setFlag("导入成功");
        tmExcelImportLogService.updateById(tmExcelImportLog);

        return R.success("导入成功");
    }

    /**
     * 导出模板
     */
    @SneakyThrows
    @GetMapping("getTaskExportTemplate")
    @ApiOperationSupport(order = 14)
    @ApiOperation(value = "任务模板下载")
    public void exportUser(HttpServletResponse response) {
        List<TmVisitTaskExcel> list = new ArrayList<>();
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding(Charsets.UTF_8.name());
        String fileName = URLEncoder.encode("任务导入模板", Charsets.UTF_8.name());
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
//        EasyExcel.write(response.getOutputStream(), TmVisitTaskExcel.class).sheet("任务导入模板").doWrite(list);
//        String path = TmVisitTaskController.class.getClassLoader().getResource("excelTemplates/taskImport.xlsx").getPath();
        String path = environment.getProperty("filePath")+"/excelTemplates/taskImport.xlsx";
        System.out.println("=========================="+path);
        byte[] fileToByteArray = FileUtils.readFileToByteArray(new File(path));
        response.getOutputStream().write(fileToByteArray);
    }

    /**
     * 根据部门id获取部门人员信息
     */
    @GetMapping("/getDeptInfoById")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "根据部门id获取部门人员信息", notes = "传入部门id")
    public List<User> getDeptInfoById(@RequestParam String deptId) {
        List<User> list = userService.list(new QueryWrapper<User>().lambda()
                .eq(User::getDeptId, deptId)
                .eq(User::getIsDeleted, 0)
                .eq(User::getStatus, 1));
        return list;
    }

    /**
     * 拒接、未接自定义分页
     */
    @GetMapping("/selectAnswerRejectPage")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "分页", notes = "传入answerRejectVO")
    public R<IPage<AnswerRejectVO>> selectAnswerRejectPage(AnswerRejectVO answerRejectVO, Query query) {
        BladeUser bladeUser = SecureUtil.getUser();
        //部门权限过滤
        if(null == answerRejectVO.getDeptId() || "".equals(answerRejectVO.getDeptId())){
            User one = userService.getOne(new QueryWrapper<User>().lambda().eq(User::getId, bladeUser.getUserId()));
            answerRejectVO.setDeptId(one.getDeptId());
        }
        IPage<AnswerRejectVO> pages = tmVisitTaskService.selectAnswerRejectPage(Condition.getPage(query), answerRejectVO);
        return R.data(pages);
    }

    /**
     * 拒接、未接查看自定义分页
     */
    @GetMapping("/selectAnswerRejectViewPage")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "分页", notes = "传入answerRejectViewVO")
    public R<IPage<AnswerRejectViewVO>> selectAnswerRejectViewPage(AnswerRejectViewVO answerRejectViewVO, Query query) {
        IPage<AnswerRejectViewVO> pages = tmVisitTaskService.selectAnswerRejectViewPage(Condition.getPage(query), answerRejectViewVO);
        return R.data(pages);
    }

    /**
     * 拒接、未接处理方法
     */
    @PostMapping("/answerRejectDispose")
    @ApiOperationSupport(order = 7)
    @ApiOperation(value = "拒接、未接处理方法", notes = "传入ids")
    public R answerRejectDispose(@ApiParam(value = "主键集合", required = true) @RequestParam String id) {
        BladeUser bladeUser = SecureUtil.getUser();
        tmVisitTaskCustomerService.update(new UpdateWrapper<TmVisitTaskCustomer>().lambda()
                .set(TmVisitTaskCustomer::getDisposeBy,bladeUser.getUserId())
                .set(TmVisitTaskCustomer::getDisposeTime,new Date())
                .set(TmVisitTaskCustomer::getDisposeStatus,"1")
                .set(TmVisitTaskCustomer::getVisitStatus,"1")
                .eq(TmVisitTaskCustomer::getId,id));
        return R.success("处理成功!");
    }

    /**
     * 重新生成日常任务
     */
    @PostMapping("/resetDailyTask")
    @ApiOperationSupport(order = 6)
    @ApiOperation(value = "新增或修改", notes = "传入tmVisitTask")
    @Transactional(rollbackFor = Exception.class)
    public R resetDailyTask(@Valid @RequestBody DailyTaskVO dailyTaskVO) {
        String[] monthArr = dailyTaskVO.getMonth().split(",");
        Date begin = DateUtil.parse(monthArr[0],DatePattern.NORM_MONTH_PATTERN);
        LocalDate beginDate = LocalDateTimeUtil.of(begin).toLocalDate();

        Date monthEndDate = DateUtil.parse(monthArr[1],DatePattern.NORM_MONTH_PATTERN);
        Date end = DateUtil.endOfMonth(monthEndDate);
        LocalDate endDate = LocalDateTimeUtil.of(end).toLocalDate();

        TmDailyTaskLog tmDailyTaskLog = new TmDailyTaskLog();
        tmDailyTaskLog.setResetType(dailyTaskVO.getResetType());
        tmDailyTaskLog.setMonth(DateUtil.format(new Date(),"yyyyMM"));
        tmDailyTaskLog.setDeptId(dailyTaskVO.getDeptId());
        tmDailyTaskLog.setDeptName(dailyTaskVO.getDeptName());
        tmDailyTaskLog.setFlag("日常任务生成-失败");
        tmDailyTaskLogService.save(tmDailyTaskLog);

        Map<String,Object> logInfo = new HashMap<>();
        if ("0".equals(dailyTaskVO.getResetType())){

            List<TmVisitTask> dailyTaskList = tmVisitTaskService.list(new LambdaQueryWrapper<TmVisitTask>()
                    .eq(TmVisitTask::getEx1,EX1_TYPE_DAILY)
                    .ge(TmVisitTask::getTaskEndDate,beginDate)
            );
            if (dailyTaskList.size()>0){
                throw new RuntimeException("生成任务的开始日期，已包含在历史任务中，不允许生成任务!");
//                logInfo.put("delete task start:",System.currentTimeMillis());
//                List<Long> dailyTaskIdList = dailyTaskList.stream().map(item->item.getId()).collect(Collectors.toList());
//                tmVisitTaskCustomerService.remove(new LambdaQueryWrapper<TmVisitTaskCustomer>().in(TmVisitTaskCustomer::getTaskId,dailyTaskIdList));
//                tmVisitTaskService.removeByIds(dailyTaskIdList);
//                logInfo.put("delete task end:",System.currentTimeMillis());
            }

            String deptSql = "select t.dept_id,t.dept_name from tm_customer t where t.cust_mgr is not null and t.cust_mgr!='' and t.del_flag=0 group by t.dept_id,t.dept_name";
            List<Map> deptList = tmCustomerCallRecordService.queryBySql(deptSql);

            logInfo.put("buildDailyTask start:",System.currentTimeMillis());
            boolean ret = buildDailyTask(deptList,beginDate,endDate);
            logInfo.put("buildDailyTask end:",System.currentTimeMillis());
            log.info("logInfo:========="+ logInfo);

            tmDailyTaskLog.setFlag("日常任务生成-成功");
            tmDailyTaskLog.setCompleteTime(LocalDateTime.now());
            tmDailyTaskLogService.saveOrUpdate(tmDailyTaskLog);
            return R.status(ret);
        }else if ("1".equals(dailyTaskVO.getResetType())){
            List<String> deptIdStrList = Func.toStrList(dailyTaskVO.getDeptId());

            List<TmVisitTask> dailyTaskList = tmVisitTaskService.list(new LambdaQueryWrapper<TmVisitTask>()
                    .eq(TmVisitTask::getEx1,EX1_TYPE_DAILY)
                    .ge(TmVisitTask::getTaskEndDate,beginDate)
                    .in(TmVisitTask::getDeptId,deptIdStrList)
            );
            if (dailyTaskList.size()>0){
                throw new RuntimeException("生成任务的开始日期，已包含在历史任务中，不允许生成任务!");
            }

            List<Dept> depts = deptService.list(new LambdaQueryWrapper<Dept>().in(Dept::getId,deptIdStrList));

            List<Map> deptList = depts.stream().map(item->{
                Map deptMap = new HashMap<String,Object>();
                deptMap.put("dept_id",item.getId());
                deptMap.put("dept_name",item.getDeptName());
                return deptMap;
            }).collect(Collectors.toList());
            boolean ret = buildDailyTask(deptList,beginDate,endDate);
            tmDailyTaskLog.setFlag("日常任务生成-成功");
            tmDailyTaskLog.setCompleteTime(LocalDateTime.now());
            tmDailyTaskLogService.saveOrUpdate(tmDailyTaskLog);
            return R.status(ret);
        }
        return R.status(false);
    }

    @Async
//    @Scheduled(cron = "00 00 03 * * ?") //凌晨3点上传
//    @Scheduled(cron = "0 03 0 1 * ?")//每月1号的0:03:00执行
    public void buildDailyTaskByMonth(){
        /**
         * 生成日常任务
         * 1、查询出配置有客户经理的，启用的客户对应的支行
         * 2、以支行数生成日常任务
         * 3、以日常任务生成日常任务明细
         */
        TmDailyTaskLog tmDailyTaskLog = new TmDailyTaskLog();
        tmDailyTaskLog.setResetType("0");
        tmDailyTaskLog.setMonth(DateUtil.format(new Date(),"yyyyMM"));

        Date begin = DateUtil.beginOfMonth(new Date());
        LocalDate beginDate = LocalDateTimeUtil.of(begin).toLocalDate();
        Date end = DateUtil.endOfMonth(new Date());
        LocalDate endDate = LocalDateTimeUtil.of(end).toLocalDate();

        List<TmVisitTask> dailyTaskList = tmVisitTaskService.list(new LambdaQueryWrapper<TmVisitTask>()
                .eq(TmVisitTask::getEx1,EX1_TYPE_DAILY)
                .eq(TmVisitTask::getTaskBeginDate,beginDate)
        );
        if (dailyTaskList.size()>0){
            List<Long> dailyTaskIdList = dailyTaskList.stream().map(item->item.getId()).collect(Collectors.toList());
            tmVisitTaskCustomerService.remove(new LambdaQueryWrapper<TmVisitTaskCustomer>().in(TmVisitTaskCustomer::getTaskId,dailyTaskIdList));
            tmVisitTaskService.removeByIds(dailyTaskIdList);
        }

        String deptSql = "select t.dept_id,t.dept_name from tm_customer t where t.cust_mgr is not null and t.cust_mgr!='' and t.del_flag=0 group by t.dept_id,t.dept_name";
        List<Map> deptList = tmCustomerCallRecordService.queryBySql(deptSql);
        boolean ret = buildDailyTask(deptList,beginDate,endDate);

        if (ret){
            tmDailyTaskLog.setFlag("日常任务生成-成功");
            tmDailyTaskLog.setCompleteTime(LocalDateTime.now());
            tmDailyTaskLogService.saveOrUpdate(tmDailyTaskLog);
        }else{
            tmDailyTaskLog.setFlag("日常任务生成-失败");
            tmDailyTaskLog.setCompleteTime(LocalDateTime.now());
            tmDailyTaskLogService.saveOrUpdate(tmDailyTaskLog);
        }
    }


    public boolean buildDailyTask(List<Map> deptList,LocalDate beginDate,LocalDate endDate){
        List<TmVisitTask> dailyTaskList = new ArrayList<>();
        String monthStr = LocalDateTimeUtil.format(beginDate, DatePattern.SIMPLE_MONTH_PATTERN);
        String dateStr = LocalDateTimeUtil.format(LocalDate.now(), DatePattern.PURE_DATE_PATTERN);
        for (int i = 0; i < deptList.size(); i++) {
            TmVisitTask dailyTask = buildDailyTaskSingle("管户任务-"+monthStr,deptList.get(i).get("dept_id").toString(),deptList.get(i).get("dept_name").toString(),beginDate,endDate);
            String taskCode = dateStr+NumberUtil.decimalFormat("00",i+1);
            dailyTask.setTaskCode(taskCode);

            dailyTaskList.add(dailyTask);
        }
        boolean dailyTaskRet = tmVisitTaskService.saveBatch(dailyTaskList);
        if (dailyTaskRet&&dailyTaskList.size()>0){
            dailyTaskList.forEach(item -> {
                //组织子表数据
                List<TmCustomer> tmCustomerList = customerService.list(new LambdaQueryWrapper<TmCustomer>()
                        .eq(TmCustomer::getDeptId,item.getDeptId()).eq(TmCustomer::getDelFlag,0));
                List<TmVisitTaskCustomer> addTaskCustomer = new ArrayList<>();

                for (TmCustomer customer : tmCustomerList) {
                    TmVisitTaskCustomer  taskCustomer=new TmVisitTaskCustomer();
                    taskCustomer.setId(IdWorker.getId());
                    taskCustomer.setTaskId(item.getId());
                    taskCustomer.setTaskCode(item.getTaskCode());
                    taskCustomer.setDeptId(Long.valueOf(item.getDeptId()));
                    taskCustomer.setDeptName(item.getDeptName());
                    taskCustomer.setCustMgr(customer.getCustMgr());
                    taskCustomer.setCustMgrName(customer.getCustMgrName());
                    taskCustomer.setCustomerCode(customer.getCustomerCode());
                    taskCustomer.setCustomerPhone(customer.getCustomerTel());
                    taskCustomer.setSex(customer.getSex());
                    taskCustomer.setVisitStatus("0");
                    //日常任务
                    taskCustomer.setEx2(EX1_TYPE_DAILY);
                    addTaskCustomer.add(taskCustomer);
                }
                tmVisitTaskCustomerService.addTaskCustomerList(addTaskCustomer);
                item.setCustNumber(tmCustomerList.size());
            });
            tmVisitTaskService.updateBatchById(dailyTaskList);
            return true;
        }
        return false;
    }

    private TmVisitTask buildDailyTaskSingle(String taskName,String deptId,String deptName,LocalDate beginDate,LocalDate endDate){
        //任务主表数据
        TmVisitTask tmVisitTask = new TmVisitTask();
        tmVisitTask.setTaskName(taskName);
        tmVisitTask.setDeptId(deptId);
        tmVisitTask.setDeptName(deptName);
        tmVisitTask.setChargeUserName("system");
        tmVisitTask.setChargeDate(LocalDate.now());
        tmVisitTask.setCustNumber(0);
        tmVisitTask.setTaskBeginDate(beginDate);
        tmVisitTask.setTaskEndDate(endDate);
        //新增1、导入2、系统生成3
        tmVisitTask.setTaskType("3");
        tmVisitTask.setTaskStatus("1");
        tmVisitTask.setScriptDesc("0");
        tmVisitTask.setDelFlag(-1);
        //日常任务
        tmVisitTask.setEx1(EX1_TYPE_DAILY);
        return tmVisitTask;
    }

    @GetMapping("/ghTaskList")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "分页", notes = "传入tmVisitTask")
    public R<IPage<TmVisitTask>> ghTaskList(TmVisitTask tmVisitTask, Query query) {
        LambdaQueryWrapper<TmVisitTask> lambdaQueryWrapper = Condition.getQueryWrapper(tmVisitTask).lambda();
        lambdaQueryWrapper.le(TmVisitTask::getTaskBeginDate,LocalDate.now());
        lambdaQueryWrapper.ge(TmVisitTask::getTaskEndDate,LocalDate.now());
        IPage<TmVisitTask> pages = tmVisitTaskService.page(Condition.getPage(query), lambdaQueryWrapper);
        return R.data(pages);
    }

    @GetMapping("/taskList")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "分页", notes = "传入tmVisitTask")
    public R<IPage<TmVisitTask>> taskList(TmVisitTask tmVisitTask, Query query) {
        QueryWrapper queryWrapper = Condition.getQueryWrapper(tmVisitTask);

        if (tmVisitTask.getDataPermission()!=null){
            if (tmVisitTask.getDataPermission()==1){}
            else if(tmVisitTask.getDataPermission()==2){
                List<Dept> deptList = deptService.list(new LambdaQueryWrapper<Dept>().eq(Dept::getParentId,tmVisitTask.getQueryParentDeptId()));
                List<Long> deptIdList = deptList.stream().map(item->item.getId()).collect(Collectors.toList());
                if (deptIdList.size()==0){
                    return R.data(null);
                }
                queryWrapper.in("dept_id",deptIdList);
            }else if(tmVisitTask.getDataPermission()==3){
                queryWrapper.eq("dept_id",tmVisitTask.getQueryDeptId());
            }
        }

        queryWrapper.orderByDesc("charge_date");
        queryWrapper.orderByAsc("seq");
        IPage<TmVisitTask> pages = tmVisitTaskService.page(Condition.getPage(query), queryWrapper);
        return R.data(pages);
    }
}
